/**
 * 
 */
package org.vsg.stock.core.algorithm;

import java.util.List;

/**
 * @author Bill Vison
 *
 */
public class ListBubble2Sort {
	
	public static final String ASC = "ASC";
	
	public static final String DESC = "DESC";
	
	private List<Sortable> sortList ;
	
	private static ListBubble2Sort listInst = null;
	
	private String type;
	
	private void setType(String type) {
		this.type = type;
	}
	
	private ListBubble2Sort() {
		
	}
	
	public List<Sortable> getSortList() {
		return sortList;
	}

	public void setSortList(List<Sortable> sortList) {
		this.sortList = sortList;
	}

	public static ListBubble2Sort getInstance(String type) {
		
		if ( listInst == null) {
			listInst = new ListBubble2Sort();
		}
		listInst.setType(type);
		return listInst;
	}
	
	public static ListBubble2Sort getInstance() {
		return getInstance(ASC);
	}
	
	public void calculate() {
		
		boolean flag;
		for (int i = 0 ; i < sortList.size() -1 ; i++ ) {
			// --- default mark ---
			flag = true;
			
			int count = 0;
			
			for (int j = sortList.size() - 1 ; j > i; j--) {

				double curr = sortList.get(j).getValue();
				double pre = sortList.get(j - 1).getValue();
				
				boolean condiction = false;

				if (type.equalsIgnoreCase("DESC")) {
					condiction = curr > pre;
				}
				else {
					condiction = curr < pre;
				}

				if ( condiction) {
					flag =false;
					swap(sortList ,j , j-1 );
				}					
				
			}
			
		}
		
	}
	
	private void swap(List<Sortable> sortList  , int i , int j ) {
		
		Sortable currData = sortList.get(i);
		Sortable preData = sortList.get(j);
		
		sortList.set( i , preData);
		sortList.set( j , currData);
	}



}
